/*
 * RecordStoreInputStream.java
 *
 * Created on 15 de mayo de 2006, 03:13 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package pe.com.nextel.rms;


import java.io.IOException;
import java.io.InputStream;
import javax.microedition.rms.RecordEnumeration;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreException;

/**
 *
 * @author marizaga
 */
public class RecordStoreInputStream extends InputStream {
    private RecordStore rs;
    private int [] ids;
    private byte [] currentRecordData;
    private int indexBufferRecordData = -1;
    private int indexId = -1;
    
    public RecordStoreInputStream(RecordStore rs) throws RecordStoreException, Exception {
        this.rs = rs;

        ids = new int[rs.getNumRecords()];

        RecordEnumeration enumeration = rs.enumerateRecords(null, null, false);

        int index = 0;

        while (enumeration.hasNextElement()) {
            ids[index++] = enumeration.nextRecordId();
        }
        
        enumeration.destroy();
        enumeration = null;

        BubbleSortAlgorithm.sort(ids);
    }

    public synchronized int read() throws IOException {
        if ((ids.length > 0) && (indexId < ids.length)) {
            try {
                if (indexId == -1 || indexBufferRecordData >= currentRecordData.length ) {
                    if ((indexId +1) == ids.length) {
                        ++indexId;
                        return -1;
                    }

                    currentRecordData = rs.getRecord(ids[++indexId]);
                    indexBufferRecordData = 0;
                }
                
                byte data = currentRecordData[indexBufferRecordData++];
                
                return (int)(data & 0xFF);

            } catch(RecordStoreException ex) {
                throw new IOException(ex.toString());
            }
        } else {
            return -1;
        }
    }
}